<template>
    <div class="upload-demo">
        <ul class="el-upload-list el-upload-list--picture">
            <li
                v-for="item of uploadingList"
                :key="item.id"
                class="el-upload-list__item is-success"
            >
                <el-image
                    class="el-upload-list__item-thumbnail"
                    :src="item.url"
                ></el-image>
                <span class="el-upload-list__item-name"
                    ><i class="el-icon-document"></i>{{ item.name }}
                </span>
                <el-progress :percentage="item.percent"></el-progress>
            </li>
            <transition-group name="list">
                <li
                    v-for="(item, index) in value"
                    :key="item.url"
                    class="el-upload-list__item is-success"
                >
                    <img
                        class="el-upload-list__item-thumbnail"
                        :src="item.url"
                        @click="onPreview(index)"
                    />
                    <div class="el-upload-list__item-name">
                        <el-input v-model="item.title"></el-input>
                    </div>
                    <label class="el-upload-list__item-status-label">
                        <i class="el-icon-upload-success el-icon-check"></i>
                    </label>
                    <el-popconfirm
                        @confirm="deleteFile(index)"
                        title="删除后无法恢复，确定删除吗？"
                    >
                        <i slot="reference" class="el-icon-close"></i>
                    </el-popconfirm>
                </li>
            </transition-group>
            <el-image-viewer
                v-if="showViewer"
                :on-close="
                    () => {
                        showViewer = false;
                    }
                "
                :url-list="getListUrl"
                :initialIndex="initialIndex"
            />
        </ul>
        <div class="el-upload__tip">
            只能上传({{ extensions }})文件，且不超过{{ fileNumLimit }}个
        </div>
        <div class="el-upload el-upload--picture">
            <div id="picker">点击上传</div>
        </div>
    </div>
</template>
<script>
import ElImageViewer from "element-ui/packages/image/src/image-viewer";
import WebUploader from "webuploader";
import config from "../../config";
import http from "../../libs/http";
export default {
    name: "MultipleImageTitle",
    props: {
        value: { type: Array, required: true },
        server: { type: String, default: config.upload.action },
        fileNumLimit: { type: Number, default: 5 },
        extensions: { type: String, default: "jpg,jpeg,png" },
        mimeTypes: { type: String, default: "" },
        width: { type: Number, default: 1600 },
        height: { type: Number, default: 1600 }
    },
    components: {
        ElImageViewer
    },
    data() {
        return {
            initialIndex: 0,
            uploader: null,
            uploadingList: {}, //上传中文件列表，
            showViewer: false
        };
    },
    computed: {
        getListUrl() {
            return this.value.map(item => {
                return item.url;
            });
        }
    },
    mounted() {
        this.uploader = WebUploader.create({
            // swf文件路径
            swf: "",
            // 文件接收服务端。
            server: this.server,
            // 文件上传最大数
            fileNumLimit: this.fileNumLimit,
            // 文件类型
            accept: {
                title: "选择文件",
                extensions: this.extensions,
                mimeTypes: this.mimeTypes
            },
            fileVal: config.upload.fieldName,
            //图片压缩
            compress: {
                width: this.width,
                height: this.height,
                quality: 90,
                allowMagnify: false,
                crop: false,
                preserveHeaders: true,
                noCompressIfLarger: false,
                compressSize: 1
            },

            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            pick: { id: "#picker", multiple: true },
            // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
            resize: false,
            //是否开启自动上传
            auto: true
        });
        this.uploaderEvent();
    },
    methods: {
        onPreview(index) {
            this.initialIndex = index;
            this.showViewer = true;
        },
        deleteFile(index) {
            http.post(config.upload.deleteAction, {
                url: this.value[index].url
            }).then(response => {
                if (response.status == 200) {
                    this.value.splice(index, 1);
                }
            });
        },
        uploaderEvent() {
            this.uploader.on("fileQueued", file => {
                let data = { id: file.id, name: file.name, percent: 0 };
                this.uploader.makeThumb(
                    file,
                    (error, ret) => {
                        if (error === true) {
                            data.url = "/images/file_icon.png";
                        } else {
                            data.url = ret;
                        }
                        this.$set(this.uploadingList, file.id, data);
                    },
                    100,
                    100
                );
            });
            this.uploader.on("uploadProgress", (file, percentage) => {
                this.uploadingList[file.id].percent = parseInt(
                    percentage.toFixed(2) * 100
                );
            });
            this.uploader.on("uploadSuccess", (file, response) => {
                if (response.state != "SUCCESS") return;
                let data = {
                    url: response.url,
                    title: file.name.split(/[.][^.]*$/)[0]
                };
                this.value.push(data);
                delete this.uploadingList[file.id];
                this.uploader.removeFile(file, true);
            });
            this.uploader.on("error", type => {
                switch (type) {
                    case "Q_EXCEED_NUM_LIMIT":
                        this.$message.error(
                            `最多只能上专${this.fileNumLimit}个文件`
                        );
                        break;
                    case "Q_TYPE_DENIED":
                        this.$message.error(
                            `只能上传${this.extensions}类型的文件`
                        );
                        break;
                }
            });
        }
    }
};
</script>
<style>
.list-enter-active,
.list-leave-active {
    transition: all 0.5s;
}
.list-enter,
.list-leave-to {
    opacity: 0;
}

.upload-demo {
    max-width: 360px;
}

#picker {
    position: relative;
    margin-top: 10px;
}

#picker .webuploader-pick {
    display: inline-block;
    line-height: 1;
    white-space: nowrap;
    cursor: pointer;
    border: 1px solid #409eff;
    color: #fff;
    background-color: #409eff;
    -webkit-appearance: none;
    text-align: center;
    box-sizing: border-box;
    outline: none;
    margin: 0;
    transition: 0.1s;
    font-weight: 500;
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    padding: 12px 20px;
    font-size: 14px;
    border-radius: 4px;
}

#picker:focus .webuploader-pick,
#picker:hover .webuploader-pick {
    background: #66b1ff;
    border-color: #66b1ff;
    color: #fff;
}

#picker .webuploader-element-invisible {
    display: none;
}
</style>
